package kubernetescli

import (
	"fmt"

	"github.com/Kindling-project/chaos-backend/api"
	"github.com/chaos-mesh/chaos-mesh/api/v1alpha1"
	"k8s.io/apimachinery/pkg/runtime/serializer"
	"k8s.io/client-go/dynamic"
	"k8s.io/client-go/kubernetes/scheme"
	"k8s.io/client-go/rest"
)

var (
	crdConfig     rest.Config
	client        *rest.RESTClient
	dynamicClient *dynamic.DynamicClient
)

var (
	NetworkChaosCli networkchaos = networkchaos{}
	StressChaosCli  stresschaos  = stresschaos{}
	JVMChaosCli     jvmchaos     = jvmchaos{}
	IOChaosCli      iochaos      = iochaos{}
	HTTPChaosCli    httpchaos    = httpchaos{}
)

const (
	NetworkChaosType = "networkchaos"
	StressChaosType  = "stresschaos"
	JvmChaosType     = "jvmchaos"
	IoChaosType      = "iochaos"
	HTTPChaosType    = "httpchaos"
)

func SetupConfig(cfg *rest.Config) error {
	v1alpha1.AddToScheme(scheme.Scheme)

	crdConfig = *cfg
	crdConfig.ContentConfig.GroupVersion = &v1alpha1.GroupVersion
	crdConfig.APIPath = "/apis"
	crdConfig.NegotiatedSerializer = serializer.NewCodecFactory(scheme.Scheme)
	crdConfig.UserAgent = rest.DefaultKubernetesUserAgent()

	var err error
	client, err = rest.UnversionedRESTClientFor(&crdConfig)
	if err != nil {
		return fmt.Errorf("error create kubernetes client: %v", err)
	}
	dynamicClient, err = dynamic.NewForConfig(cfg)
	if err != nil {
		return fmt.Errorf("error create dynamic kubernetes client: %v", err)
	}
	return nil
}

// ChaosCli 管理由ChaosMesh定义的故障CRD资源
type ChaosCli interface {
	List() (interface{}, error)
	// 根据抽象后的Chaos数据创建合适的Chaos CRD资源,并返回创建结果
	Create(*api.Chaos) (interface{}, error)
	DeleteAll() (interface{}, error)
	// ToChaosVO 将ChaosMesh定义的CRD转换成抽象的Chaos数据
	// 对CRD包含的信息进行抽象和简化,便于前端读取
	ToChaosVO(obj *interface{}) []api.Chaos
}
